using System.Linq;
using Omu.AwesomeDemo.Core.Model;
using Omu.AwesomeDemo.Core.Repository;

namespace Omu.AwesomeDemo.Service
{
    public class FoobarService : CrudService<Foobar>
    {
        private readonly IRepo<Hobby> hobbyRepo;

        public FoobarService(IRepo<Foobar> repo, IRepo<Hobby> hobbyRepo) : base(repo)
        {
            this.hobbyRepo = hobbyRepo;
        }

        public override int Create(Foobar e)
        {
            e.Hobby = ResolveHobby(e.Hobby);

            return repo.Insert(e);
        }

        public override void Save(Foobar e)
        {
            e.Hobby = ResolveHobby(e.Hobby);
            repo.Update(e);
        }

        private Hobby ResolveHobby(Hobby hobby)
        {
            if (hobby == null) return null;

            if (hobby.Id != 0)
                return hobbyRepo.Get(hobby.Id);

            if (!string.IsNullOrWhiteSpace(hobby.Name))
            {
                var h = hobbyRepo.GetAll().FirstOrDefault(o => o.Name.ToLowerInvariant() == hobby.Name);
                
                //if hobby with this name not found insert a new one
                return h ?? hobbyRepo.Get(hobbyRepo.Insert(new Hobby { Name = hobby.Name }));
            }
            return null;
        }
    }
}